import { defineStore } from 'pinia'
import { wxLoginAPI } from '@/service/index/user'
const initState = { nickname: '', avatar: '', id: '', token: '' }

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState })
    const wxLogin = async (): Promise<void> => {
      try {
        uni.showLoading({ title: '登录中...' })
        // 1. 获取微信登录code（小程序）
        const { code } = await uni.login({ provider: 'weixin' })
        // if (!code) throw new Error('微信登录失败：未获取到code')

        // const { iv, encryptedData } = await uni.getUserProfile({ provider: 'weixin' })

        // if (!iv && !encryptedData) throw new Error('微信登录失败：未获取到iv或encryptedData')

        // const userResult = await wxLoginAPI({ code, encryptedData, iv })
        const userResult = await wxLoginAPI({ code })
        setUserInfo(userResult.data)
        uni.showToast({ title: '登录成功', icon: 'none' })
        setTimeout(() => {
          uni.reLaunch({ url: '/pages-sub/personal-record/index' })
        }, 100)
      } catch (error) {
        console.error('微信登录失败:', error)
        uni.showToast({ title: '登录失败', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    }
    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }

    const isLogined = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      wxLogin,
    }
  },
  {
    persist: true,
  },
)
